from abc import ABC, abstractmethod


class DatabaseConnector(ABC):

    def __init__(self, name):
        self.connector_name = name


    def get_connector_name(self):
        return self.connector_name

    """
    数据库连接器接口，定义所有数据库连接器必须实现的方法。
    """
    @abstractmethod
    def get_db_type(self):
        pass

    @abstractmethod
    def test_connection(self):
        pass

    @abstractmethod
    def fetch_table_schema(self, table):
        pass

    @abstractmethod
    def get_tables_info(self):
        """获取数据库中的表信息"""
        pass

    @abstractmethod
    def get_table_ddl(self, table_name: str) -> str:
        """获取指定表的建表脚本"""
        pass

    @abstractmethod
    def get_table_fields(self,table_name):
        pass

    @abstractmethod
    def close(self):
        """关闭数据库连接"""
        pass

    @staticmethod
    def create_connector(db_config,pool_size=5):

        db_type = db_config.get("type", "").lower()

        if db_type == "mysql":
            # 提取 MySQL 连接所需的字段
            mysql_config = {
                key: db_config[key]
                for key in ["host", "user", "password", "port", "database"]
                if key in db_config
            }
            mysql_config["pool_size"] = db_config.get("pool_size", pool_size)
            from core.connectors.mysql_connector import MySQLConnector
            return MySQLConnector(**mysql_config)

        elif db_type == "postgresql":
            # 提取 PostgreSQL 连接所需的字段
            postgres_config = {
                key: db_config[key]
                for key in ["host", "port", "user", "password", "database"]
                if key in db_config
            }
            from core.connectors.postgresql_connector import PostgresqlConnector
            return PostgresqlConnector(**postgres_config)

        else:
            raise ValueError(f"Unsupported database type: {db_type}")
